<?php

namespace App\Http\Controllers\Api;

use App\Constants\MemberTaskConstant;
use App\Constants\MiniProgramConstant;
use App\Events\DailyTask;
use App\Http\Requests\Api\AuthorizationRequest;
use App\Jobs\Tcm\InitMemberBookCollect;
use App\Models\Member;
use EasyWeChat\Factory;
use Illuminate\Http\Request;


class AuthorizationsController extends Controller
{
    public function store(Request $requests)
    {
        $post = $requests->post();
        $settings = getMiniSettings($this->getMiniType(), MiniProgramConstant::GROUP);

//        $miniProgram = \EasyWeChat::miniProgram();
        $miniProgram = Factory::miniProgram(array_merge([
            'app_id' => $settings[MiniProgramConstant::APP_ID],
            'secret' => $settings[MiniProgramConstant::APP_SECRET],
        ], config('wechat.defaults')));
        $data = $miniProgram->auth->session($post['code']);

        if (isset($data['errcode'])) {
            return $this->error('code已过期或不正确');
        }

        $member = Member::where([
            'open_id' => $data['openid'],
            'mini_type' => $this->getMiniType(),
        ])->with('publisher')->first();

        $phone = $post['phone'] ?? '';

        if (!$member) {

            if (isset($post['invite_id']) && $post['invite_id']) {
                if (Member::query()->where([
                    'id'        => $post['invite_id'],
                    'mini_type' => $this->getMiniType(),
                ])->exists()) {
                    $inviteId = $post['invite_id'];
                }
            }

            $avatar = $settings[MiniProgramConstant::DEFAULT_HEAD_PICTURE] ?? '';
            if (!$avatar) {
                $avatar = url('images/user_default.png');
            }

            $member = Member::create([
                'nickname' => '游客' . mt_rand(100000,999999),
                //'sex' => $post['sex'] ?: '',
                'avatar' => $avatar,
                'open_id' => $data['openid'],
                'session_key' => $data['session_key'],
                'mini_type' => $this->getMiniType(),
                'invite_id' => $inviteId ?? 0,
                'phone' => $phone,
            ]);

            if (isset($inviteId)) {
                event(new DailyTask($this->getMiniType(), $inviteId, MemberTaskConstant::SLUG_BY_INVITE_REGISTER));
            }

            InitMemberBookCollect::dispatch([$member->id]);
        } else {
            if ($member->status == 0) {
                return $this->error('您的账号已被锁定，如有疑问请联系客服', [], 40002, 401);
            }
            if (!$member->publisher) {
                $member = Member::UpdateOrCreate(['open_id' => $data['openid'], 'mini_type' => $this->getMiniType()], [
                    //'nickname' => $post['nickname'] ?: '',
                    //'avatar' => $post['avatar'] ?: '',
                    'open_id' => $data['openid'],
                    'session_key' => $data['session_key'],
                    'mini_type' => $this->getMiniType(),
                ]);
            }

            if ($phone) {
                $member->update(['phone' => $phone]);
            }
        }

        $token = auth('api')->login($member);
        return $this->respondWithToken($token);
    }

    public function update()
    {
        $token = auth('api')->refresh();
        return $this->respondWithToken($token);
    }

    public function destroy()
    {
        auth('api')->logout();
        return $this->success('登出成功');
    }

    protected function respondWithToken($token)
    {
        return $this->success('登录成功', [
            'access_token' => 'Bearer ' . $token,
            'token_type' => 'Bearer',
            'expires_in' => auth('api')->factory()->getTTL() * 1200
        ]);
    }
}
